package com.qk.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.dto.UserDto;
import com.qk.entity.User;
import com.qk.exception.BusinessException;
import com.qk.mapper.UserMapper;
import com.qk.service.UserService;
import com.qk.utils.JwtUtils;
import com.qk.vo.LoginResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询用户列表
     */
    @Override
    public PageResult<User> list(UserDto userDto) {
        //1.设置PageHelper分页参数
        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());
        //2.调用mapper接口方法，执行查询
        List<User> userList = userMapper.selectList(userDto);
        //3.解析并封装分页结果
        Page<User> p = (Page<User>) userList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    /**
     * 添加用户
     */
    @Override
    public void add(User user) {
        //补充数据
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        //设置默认密码
        String password = user.getUsername() + "123";
        //md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));

        //调用mapper接口方法，执行添加
        userMapper.insert(user);
    }

    /**
     * 批量删除用户
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    public User selectById(Integer id) {
        return userMapper.selectById(id);
    }

    /**
     * 修改用户
     */
    @Override
    public void update(User user) {
        //补全数据
        user.setUpdateTime(LocalDateTime.now());
        //设置默认密码
        String password = user.getUsername() + "123";
        //md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userMapper.update(user);
    }

    /**
     * 查询所有用户
     */
    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    /**
     * 根据角色查询用户
     */
    @Override
    public List<User> selectByRole(String roleLabel) {
        return userMapper.selectByRole(roleLabel);
    }

    /**
     * 根据部门查询用户
     */
    @Override
    public List<User> selectByDept(Integer deptId) {
        return userMapper.selectByDept(deptId);
    }

    /**
     * 登录
     */
    @Override
    public LoginResultVo login(User user) {
        //1.调用Mapper，根据用户名查询用户
        User u = userMapper.selectByUsername(user.getUsername());

        //2.判断用户是否存在
        if (u == null) {
            log.info("用户不存在");
            throw new BusinessException("用户名或密码错误");
        }
        //3.判断密码是否正确
        //将输入的密码进行md5加密
        String pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (!pass.equals(u.getPassword())) {
            log.info("密码错误");
            throw new BusinessException("用户名或密码错误");
        }

        //4.判断状态是否正常
        if (u.getStatus() != 1) {
            log.info("用户已停用");
            throw new BusinessException("用户已停用");
        }

        //5.封装结果并返回
        LoginResultVo loginResultVo = new LoginResultVo();
        loginResultVo.setId(u.getId());
        loginResultVo.setUsername(u.getUsername());
        loginResultVo.setName(u.getName());
        loginResultVo.setImage(u.getImage());
        loginResultVo.setRoleLabel(u.getRoleLabel());

        //调用工具类，生成jwt令牌
        Map<String, Object> clarims = new HashMap<>();
        clarims.put("id", u.getId());
        clarims.put("username", u.getUsername());
        String jwt = JwtUtils.generateToken(clarims);

        loginResultVo.setToken(jwt);

        return loginResultVo;
    }
}
